﻿using Mozhi.Abp.Core.Networks;
using System;
using Volo.Abp;
using Volo.Abp.Caching;
using Volo.Abp.Users;

namespace Mozhi.Abp.Organization
{
    public class CurrentOrganization : ICurrentOrganization
    {
        public Guid? Id { get { return GetData()?.Id; } }

        public Guid? TenantId { get { return GetData()?.TenantId; } }

        public string Name { get { return GetData()?.Name; } }

        public string OfficialName { get { return GetData()?.OfficialName; } }

        public DateTime? ActivatedDate { get { return GetData()?.ActivatedDate; } }

        public int? AccountingStandard { get { return GetData()?.AccountingStandard; } }

        public Guid? StandardCurrencyId { get { return GetData()?.StandardCurrencyId; } }

        public string TaxIDNumber { get { return GetData()?.TaxIDNumber; } }

        public int? ActivatedPeriod 
        { 
            get
            {
                if (!ActivatedDate.HasValue)
                    return null;

                return int.Parse(ActivatedDate.Value.ToString("yyyyMM"));
            } 
        }

        public bool IsValidate()
        {
            return StandardCurrencyId.HasValue && ActivatedDate.HasValue;
        }

        public void Validator()
        {
            if (!StandardCurrencyId.HasValue)
                throw new UserFriendlyException("组织未设置本位币", "100000");

            if (!ActivatedDate.HasValue)
                throw new UserFriendlyException("组织未设置启用日期", "100000");
        }

        private ICurrentUser _currentUser;
        private IDistributedCache<OrganizationData> _distributedCache;
        private IRemoteServiceClient _remoteClient;

        public CurrentOrganization(ICurrentUser currentUser,  IDistributedCache<OrganizationData> distributedCache, IRemoteServiceClient remoteClient)
        {
            _currentUser = currentUser;
            _distributedCache = distributedCache;
            _remoteClient = remoteClient;
        }

        

        #region

        private OrganizationData GetData()
        {
            var tenantId = _currentUser.TenantId;

            if (tenantId == null)
                return null;

            var key = "Organiztion_" + tenantId;

            var organization = _distributedCache.Get(key);

            if (organization != null)
                return organization;

            var url = "/api/organization";

            organization = _remoteClient.GetAsync<OrganizationData>("BasicData" , url).Result;

            return organization;
        }

        #endregion
    }

    public class OrganizationData
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string OfficialName { get; set; }
        public DateTime? ActivatedDate { get; set; }
        public int? AccountingStandard { get; set; }
        public Guid? StandardCurrencyId { get; set; }
        public string TaxIDNumber { get; set; }
        public Guid? TenantId {  get; set; }
    }
}
